import { createParamDecorator, ExecutionContext, UnauthorizedException } from '@nestjs/common';
import * as jwt from 'jsonwebtoken';

interface JwtPayload {
  userid: string;
  // add other JWT payload fields if needed
}

export const CurrentUser = createParamDecorator(
  (data: unknown, ctx: ExecutionContext) => {
    const request = ctx.switchToHttp().getRequest();
    const token = request.headers.authorization;
    if (!token) {
      throw new UnauthorizedException('No token provided');
    }
    try {
      const decoded = jwt.verify(token, process.env.JWT_SECRET) as JwtPayload;
      if (!decoded.userid) {
        throw new UnauthorizedException('Invalid token: no userid found');
      }
      return decoded.userid;
    } catch (error) {
      throw new UnauthorizedException('Invalid token');
    }
  },
); 